/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.emergency.controller;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.google.gson.Gson;
import com.koron.common.Excel;
import com.koron.common.StaffAttribute;
import com.koron.common.bean.StaffBean;
import com.koron.common.domain.DataBean;
import com.koron.common.permission.SPIAccountAnno;
import com.koron.emergency.domain.DrillAssessment;
import com.koron.emergency.service.api.DrillAssessmentService;
import com.koron.emergency.util.BusinessCode;
import com.koron.system.annotation.Log;
import com.koron.system.discrete.BusinessManipulation;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;
import springfox.documentation.annotations.ApiIgnore;

import java.io.File;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Api(tags = "drillAssessment",description = "演练评估相关接口")
@RestController
@RequestMapping("/drillAssessment")
public class DrillAssessmentController {
    @Autowired
    private DrillAssessmentService service;
    private final static Logger logger = LoggerFactory.getLogger(DrillPlanController.class);


    @ApiOperation("保存演练评估接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id,新增不传，修改必传",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "corpCode", value = "水司code", required = true, dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "drillPlanId", value = "演练计划id",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "name", value = "演练评估名称", required = true, dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "manager", value = "演练负责人code", required = true, dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "managerName", value = "演练负责人名称", required = true, dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "sponsorDeptCode", value = "主办部门code", required = true, dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "sponsorDeptName", value = "主办部门名称", required = true, dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "cooperationDeptCode", value = "协办部门code,多个之间用，分开",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "cooperationDeptName", value = "协办部门名称,多个之间用，分开",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "purpose", value = "演练目的", required = true, dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "contingencyPlanId", value = "应急预案id", required = true, dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "place", value = "演练地点", required = true, dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "drillTime", value = "演练时间，格式为yyyy-MM-dd HH:mm:ss", required = true, dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "drillMethod", value = "演练方式，0桌面演练1功能演练2全面演练", required = true, dataType = "int",paramType = "query"),
            @ApiImplicitParam(name = "drillCause", value = "演练经过",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "drillEffect", value = "演练效果评估",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "remrak", value = "备注",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "participant", value = "参与人员code，可存在多个,多个之间用，分开",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "participantName", value = "参与人员姓名和部门姓名，staffname_deptname,多个之间用，分开",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "files", value = "要上传的文件",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "keepFiles", value = "要保存的文件地址",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "delFiles", value = "要删除的文件地址",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "pdfKeepFiles", value = "要删除的pdf文件地址",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "pdfDelFiles", value = "要删除的pdf文件地址",  dataType = "String",paramType = "query")
    }
    )
    @RequestMapping(value = "/save.htm",method = RequestMethod.POST)
    @Log(title = "保存演练评估", businessModule = "演练评估", businessManipulation = BusinessManipulation.INSERT)
    public MessageBean<Integer> save(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @ApiIgnore DrillAssessment bean, MultipartFile [] files,
                                     @RequestParam(required = false) final String keepFiles,@RequestParam(required = false) final String delFiles,
                                     @RequestParam(required = false) final String pdfKeepFiles,@RequestParam(required = false) final String pdfDelFiles){
        if (null==user){
            MessageBean<Integer> messageBean=new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LONGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return messageBean;
        }
        if (StringUtils.isNotEmpty(bean.getCooperationDeptCode())){
            String[] codes=bean.getCooperationDeptCode().split("[,，]");
            bean.setCooperationDeptCode(new Gson().toJson(Arrays.asList(codes)));
        }
        if (StringUtils.isNotEmpty(bean.getCooperationDeptName())){
            String[] names=bean.getCooperationDeptName().split("[,，]");
            bean.setCooperationDeptName(new Gson().toJson(Arrays.asList(names)));
        }
        if (StringUtils.isNotEmpty(bean.getParticipant())){
            String[] codes=bean.getParticipant().split("[,，]");
            bean.setParticipant(new Gson().toJson(Arrays.asList(codes)));
        }
        if (StringUtils.isNotEmpty(bean.getParticipantName())){
            String[] names=bean.getParticipantName().split("[,，]");
            bean.setParticipantName(new Gson().toJson(Arrays.asList(names)));
        }
        bean.setUpdateUser(user.getCode());
        bean.setUpdateUserName(user.getName());
        bean.setUpdateTime(new Date());
        return service.save(bean,files,keepFiles,delFiles,pdfKeepFiles,pdfDelFiles);
    }

    @ApiOperation("删除演练评估接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "演练评估id",required = true,dataType = "String",paramType = "query"),
    })
    @RequestMapping(value = "/delete.htm",method = RequestMethod.POST)
    @Log(title = "删除演练评估", businessModule = "演练评估", businessManipulation = BusinessManipulation.DELETE)
    public MessageBean<Integer> deleteEmergency(@RequestParam final String id){

        return service.delete(id);
    }

    @ApiOperation("查询单个演练评估详情接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "演练评估id",required = true,dataType = "String",paramType = "query"),
    })
    @RequestMapping(value = "/details.htm",method = RequestMethod.POST)
    public MessageBean<DrillAssessment> details(@RequestParam final String id){

        return service.queryOne(id);
    }

    @ApiOperation("演练评估列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "corpCode",value = "水司code",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "name",value = "计划名称",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "sponsorDeptCode",value = "主办单位code",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "drillMethod",value = "演练方式",dataType = "int",paramType = "query"),
            @ApiImplicitParam(name = "startTime",value = "演练开始时间，格式为：yyyy-MM-dd",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "endTime",value = "演练结束时间，格式为：yyyy-MM-dd",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "page",value = "当前页",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "pageSize",value = "每页条数",required = true,dataType = "String",paramType = "query"),
    })
    @RequestMapping(value = "/list.htm",method = RequestMethod.POST)
    public MessageBean<DataBean<DrillAssessment>> list(@RequestParam(required = false) final String corpCode, @RequestParam(required = false) final String name, @RequestParam(required = false) final String sponsorDeptCode,
                                                @RequestParam(required = false) final Integer drillMethod, @JsonFormat(pattern="yyyy-MM-dd",timezone="GMT+8") @DateTimeFormat(pattern="yyyy-MM-dd")@RequestParam(required = false) final Date startTime,
                                                 @JsonFormat(pattern="yyyy-MM-dd",timezone="GMT+8")  @DateTimeFormat(pattern="yyyy-MM-dd")@RequestParam(required = false) final Date endTime,
                                                 @RequestParam Integer page, @RequestParam Integer pageSize){
        Integer start=null;
        if (page==null||page<=0){
            page=1;
            if (pageSize==null||pageSize<=0){
                pageSize=15;
            }
        }
        start=(page<=1)?0:(page-1)*pageSize;
        MessageBean<DataBean<DrillAssessment>>msg= service.queryByCondition(corpCode, name,sponsorDeptCode, drillMethod,startTime, endTime, start, pageSize);
        if (null!=msg.getData())
            msg.getData().setPageNo(page);
        return msg;
    }

    @ApiOperation("导出演练评估")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "corpCode",value = "水司code",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "name",value = "计划名称",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "sponsorDeptCode",value = "主办单位code",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "drillMethod",value = "演练方式",dataType = "int",paramType = "query"),
            @ApiImplicitParam(name = "startTime",value = "演练开始时间，格式为：yyyy-MM-dd",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "endTime",value = "演练结束时间，格式为：yyyy-MM-dd",dataType = "String",paramType = "query"),
    })
    @RequestMapping(value = "/export.htm",method = RequestMethod.GET)
    public HttpEntity<?> export(@RequestParam(required = false) final String corpCode, @RequestParam(required = false) final String name, @RequestParam(required = false) final String sponsorDeptCode,
                                @RequestParam(required = false) final Integer drillMethod, @JsonFormat(pattern="yyyy-MM-dd",timezone="GMT+8") @DateTimeFormat(pattern="yyyy-MM-dd")@RequestParam(required = false) final Date startTime,
                                @JsonFormat(pattern="yyyy-MM-dd",timezone="GMT+8")  @DateTimeFormat(pattern="yyyy-MM-dd")@RequestParam(required = false) final Date endTime){
        Map<String,Object> map=new HashMap<>();
        MessageBean<DataBean<DrillAssessment>> msg=service.queryByCondition(corpCode, name,sponsorDeptCode,drillMethod, startTime, endTime,null,null);
        if (msg.getData()!=null){
            map.put("data",msg.getData().getList());
        }
        File targetFile = new File("static/excel/drillAssessment.xlsx");
        try {
            InputStream in = getClass().getClassLoader().getResourceAsStream("static/excel/drillAssessment.xlsx");
            FileUtils.copyInputStreamToFile(in, targetFile);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        return Excel.createFile("导出演练评估列表",targetFile, "drillAssessment.btl",map);
    }
}
